import { userProfileImport } from "@/services/userProfile";
import { Button, Modal, Upload,Icon, message } from "antd";
import React from "react";

class BatchModal extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      fileList:[],
      btnLoading:false
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  openModal = () => {
    this.setState({
      visible:true
    })
  }

  doCancel = () => { 
    this.setState({
      visible:false,
      fileList:[],
      btnLoading:false
    })
  }

  doOk = () => {
    const { fileList } = this.state;
    const { applicationId } = this.props;
		const formData = new FormData();
		fileList.forEach((file) => {
			formData.append("file", file.originFileObj);
			formData.append("applicationId", applicationId)
		});
    this.setState({
      btnLoading:true
    },async () => {
      const res = await userProfileImport(formData)
      if(res.code == -1){
        this.setState({
          fileList:[],
          btnLoading:false
        })
      }else{
        message.info(res.msg)
        this.doCancel()
        this.props.refreshList()
      }
    })
    
    
  }

  handleUpFile = (info) => {
		let fileList = [...info.fileList];
		fileList = fileList.slice(-1);
		fileList = fileList.map((file) => {
			if (file.response) {
				file.url = file.response.url;
			};
			return file;
		});
		this.setState({ fileList });
	};

  render(){
    const { visible,fileList,btnLoading } = this.state;
    const props = {
      accept:".xlsx",
			onRemove: (file) => {
				this.setState((state) => {
					const index = state.fileList.indexOf(file);
					const newFileList = state.fileList.slice();
					newFileList.splice(index, 1);
					return {
						fileList: newFileList,
					};
				});
			},
			beforeUpload: (file) => {
				this.setState((state) => ({
					fileList: [...state.fileList, file],
				}));
				return false;
			},
			fileList,
			onChange: this.handleUpFile,
		};
    return(
      <Modal
        title='批量上传'
        visible={visible}
        onCancel={this.doCancel}
        onOk={this.doOk}
        confirmLoading={btnLoading}
      >
        <p>1、仅限定上传表格.xlsx</p>
        <p>2、校验手机号是否重复</p>
        <p>3、表格信息中存在空值时无法导入</p>
        <p>4、<a href="/cloud/用户信息导入模板.xlsx" target="_blank">下载模板</a></p>
        <Upload {...props}>
          <Button>
            <Icon type="upload" />上传文件
          </Button>
        </Upload>
      </Modal>
    )
  }
}

export default BatchModal